package com.gzu.ltms.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.gzu.ltms.constant.RedisKeyConstants;
import com.gzu.ltms.entity.Courier;
import com.gzu.ltms.entity.OrderDetail;
import com.gzu.ltms.entity.dto.OrderDTO;
import com.gzu.ltms.holder.LoginUserContextHolder;
import com.gzu.ltms.mapper.CourierMapper;
import com.gzu.ltms.mapper.OrderDetailMapper;
import com.gzu.ltms.response.Response;
import com.gzu.ltms.service.OrderDetailService;
import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * 订单主表 服务层实现。
 *
 * @author mm
 * @since 2025-04-28
 */
@Service
public class OrderDetailServiceImpl extends ServiceImpl<OrderDetailMapper, OrderDetail> implements OrderDetailService {

    @Resource
    private OrderDetailMapper orderDetailMapper;
    @Resource
    private CourierMapper courierMapper;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;


    @Override
    public Response<?> createOrder(OrderDTO orderDTO) {
        // 获取用户id
        Long userId = LoginUserContextHolder.getUserId();

        // 获取配送员id
        Long courierId = QueryChain.of(courierMapper)
                .eq(Courier::getIsAvailable, 1)
                .one().getCourierId();

        OrderDetail orderDetail = OrderDetail.builder()
                .userId(userId)
                .courierId(courierId)
                .createTime(LocalDateTime.now())
                .build();

        BeanUtils.copyProperties(orderDTO, orderDetail);

        orderDetailMapper.insert(orderDetail);

        return Response.success();
    }

    /**
     * 获取所有订单
     * @return
     */
    @Override
    public Response<List<OrderDetail>> getAllOrder() {
        // 获取用户id
        Long userId = LoginUserContextHolder.getUserId();
        // 先从redis中获取数据
        // 构建redis key
        String redisKey = RedisKeyConstants.buildOrderKey(userId);
        String redisJson = (String) redisTemplate.opsForValue().get(redisKey);
        if (StringUtils.isNotBlank(redisJson)) {
            // 解析Json数据
            List<OrderDetail> orderDetailList = JSONUtil.toList(redisJson, OrderDetail.class);
            return Response.success(orderDetailList);
        }

        // 从数据库中获取数据
        List<OrderDetail> orderDetailList = QueryChain.of(orderDetailMapper)
                .eq(OrderDetail::getUserId, userId)
                .list();

        if (!Objects.isNull(orderDetailList)) {
            threadPoolTaskExecutor.execute(() -> {
                // 防止缓存穿透，将空值设置到 Redis 中
                // 有效期为：保底1分钟加上随机时间
                long expireTime = 60 + RandomUtil.randomInt(60);
                redisTemplate.opsForValue().set(redisKey, JSONUtil.toJsonStr(orderDetailList), expireTime);
            });
        }
        return Response.success(orderDetailList);
    }


    /**
     * 根据id获取订单
     * @param id
     * @return
     */
    @Override
    public Response<OrderDetail> getOrderById(Long id) {
        OrderDetail orderDetail = QueryChain.of(orderDetailMapper)
                .eq(OrderDetail::getOrderId, id)
                .one();
        return Response.success(orderDetail);
    }
}
